import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { STComponent } from '@delon/abc/st';
import { UsermanageService } from '../../../../services/usercenter.service';
import { SFComponent, SFSchema, SFDateWidgetSchema, SFUISchema, SFUploadWidgetSchema } from '@delon/form';
import { Observable, Observer } from 'rxjs';
@Component({
  selector: 'app-Freight-components-list-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.less'],
})
export class FreightComponentsListViewComponent implements OnInit {
  i: any;
  url = `/rule?_allow_anonymous=true`;

  @ViewChild('st', { static: false }) st!: STComponent;
  detailData: any = {
    status: 0
  };
  isShow = false;
  isVisible = false;
  modalTitle = '有效期';
  modalName = '';
  ui!: SFUISchema;
  schema!: SFSchema;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sf1', { static: false }) sf1!: SFComponent;
  validData: any = ['FreightsType'];
  FreightsData: any = {};

  constructor(
    public service: UsermanageService,
    private route: ActivatedRoute,
  ) {}

  ngOnInit() {
    this.initData();
    this.initSF();
    // this.launchSign();
  }
  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
      name: {
        title: '许可证号',
        type: 'string',
        maxLength: 20,
        ui: {
          placeholder: '请输入角色名称',
        },
      },
      phone: {
        title: '业户名称',
        type: 'string',
        maxLength: 20,
        ui: {
          placeholder: '请输入业户名称',
        },
      },
      roleDescription: {
        title: '地址',
        type: 'string',
        maxLength: 30,
        ui: {
          placeholder: '请输入地址',
          widget: 'textarea',
        },
      },
      effectiveDate: {
          title: '发证日期',
          type: 'string',
          ui: {
            widget: 'date',
            format: 'yyyy-MM-dd 00:00:00',
            // hidden: this.modalName === 'effectiveDate' ? false : true,
          } as SFDateWidgetSchema,
      },
      phone3: {
        title: '有效期',
        type: 'string',
        ui: {
          placeholder: '请输入业户名称',
        },
      }, 
      phone4: {
        title: '有效期截止',
        type: 'string',
        ui: {
          placeholder: '请输入业户名称',
        },
      }, 
      phone5: {
        title: '经营范围',
        type: 'string',
        ui: {
          placeholder: '请输入业户名称',
        },
      }, 
      avatar: {
        type: 'string',
        title: '证照',
        ui: {
          // action: environment.UPLOAD_URL,
          fileType: 'image/png,image/jpeg,image/jpg,image/png,image/gif,image/bmp',
          limit: 1,
          limitFileCount: 1,
          resReName: 'url',
          urlReName: 'url',
          widget: 'upload',
          descriptionI18n: '图片支持jpg、jpeg、png、gif格式，大小不超过5M',
          data: {
            // appId: environment.appId,
          },
          name: 'multipartFile',
          multiple: false,
          listType: 'picture-card',
          change: (args) => {
            if (args.type === 'success') {
              const avatar = [
                {
                  uid: -1,
                  name: 'LOGO',
                  status: 'done',
                  url: args.fileList[0].response.url,
                  response: {
                    url: args.fileList[0].response.url,
                  },
                },
              ];
              this.sf?.setValue('/avatar', avatar);
            }
          },
          beforeUpload: (file: any, _fileList) => {
            return new Observable((observer: Observer<boolean>) => {
              const isLt2M = file.size / 1024 / 1024 < 5;
              if (!isLt2M) {
                this.service.msgSrv.warning('图片大小超过5M!');
                observer.complete();
                return;
              }
              observer.next(isLt2M);
              observer.complete();
            });
          },
        } as SFUploadWidgetSchema,
      },
      },
      required: ['name', 'phone'],
    };
    this.ui = { '*': { spanLabelFixed: 200, grid: {offset:4, span: 12 } } };
  }
  showModal(name: any) {
    this.modalName = name;
    if (name === 'effectiveDate') {
      this.isShow = true;
    } else {
      this.isVisible = true;
    }
  }
  async initData() {
    console.log(this.route.snapshot, 'this.route.snapshot');

    const params = {
      tenantId: this.route.snapshot.params.id,
    };
  }

  /**
   * 根据地区code查询地区详情
   * @param code 地区代码
   */
  async getRegionFullName(code: any) {
    const params = {
      regionCode: code,
    };
    const res = await this.service.asyncRequest(this.service.$api_get_one, params, 'POST', true);
    // if (res && res.regionFullName) {
    //   const arr = res.regionFullName.split(',');
    //   res.regionFullName = arr.reverse().join('-');
    // }
    return res && res.regionFullName;
  }
  add() {
    // this.modal
    //   .createStatic(FormEditComponent, { i: { id: 0 } })
    //   .subscribe(() => this.st.reload());
  }
  goBack() {
    window.history.go(-1);
  }
  /**
   * 冻结
   */
  freezeOrResume(type: number) {
    this.service.http
      .post(this.service.$api_get_one, {
        tenantId: this.route.snapshot.params.id,
        // tenantId: this.route.snapshot.queryParams.tenantId,
        status: type,
      })
      .subscribe((res) => {
        if (res.data === true) {
          if (type === 0) {
            this.service.msgSrv.success(`启用成功！`);
          } else if (type === 1) {
            this.service.msgSrv.success(`冻结成功！`);
          }
          this.ngOnInit();
        } else {
          this.service.msgSrv.error(res.msg || '操作失败！');
        }
      });
  }

  handleCancel(name: any) {
    if (name === 'effectiveDate') {
      this.isShow = false;
    } else {
      this.isVisible = false;
    }
  }
  handleOK(name: any) {
    const params: any = {
      tenantId: this.route.snapshot.params.id,
      // tenantId: this.route.snapshot.queryParams.tenantId,
    };

    if (name === 'effectiveDate') {
      params.effectiveDate = this.sf?.value?.effectiveDate;
    } else {
      Object.assign(params, this.sf1?.value);
    }
    this.service.http.post(this.service.$api_get_one, params).subscribe((res) => {
      if (res.data === true) {
        this.service.msgSrv.success(`编辑成功！`);
        this.ngOnInit();
      } else {
        this.service.msgSrv.error(res.msg || '编辑失败！');
      }
      if (name === 'effectiveDate') {
        this.isShow = false;
      } else {
        this.isVisible = false;
      }
    });
  }
}
